<template>
	<div v-loading="loading">
		<el-upload :headers = "headers" :action="uploadIMGURL" :show-file-list="true" :file-list="fileList" list-type="picture-card" accept=".jpg,.png,.jpeg" multiple name="fileData" :before-upload="beforeUploade" :on-success="handleAvatarSuccess" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
			<i class="el-icon-plus"></i>
		</el-upload>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>

<script>
import axios from 'axios';
import {getToken} from '../utils/http.js';
export default {
	data() {
		return {
			loading: false,
			dialogImageUrl: '',
			dialogVisible: false,
			uploadIMGURL: this.$constant.uploadIMGURL,
			fileList:[],
			uploadFile: [],
			headers:{
				token:getToken(),
			}
		}
	},
	props:{
		updateData:''
	},
	watch:{
		updateData(){
			if(this.updateData){
				for(var i in this.updateData){
					this.fileList.push({name:this.updateData[i].attaName,url:this.updateData[i].attaUrl})
					this.uploadFile.push(this.updateData[i].attaUrl);
				}
			}
			console.log(this.uploadFile)
		}
	},
	
	mounted() {
	},
	methods: {
		// 删除回调
		handleRemove(file, fileList) {
			console.log(file,fileList);
			let newUrl = file.url;
			let index = this.uploadFile.indexOf(newUrl);
			this.uploadFile.splice(index, 1);
			this.$emit('delImg',this.uploadFile[index])
		},
		//显示
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.dialogVisible = true;
		},
		// 上传之前
		beforeUploade(file) {
			this.loading = true;
			const isLt2M = file.size / 1024 / 1024 < 3;
			if (!isLt2M) {
				this.$message.error("上传头像图片大小不能超过 2MB!");
			}
			return isLt2M;
		},
		// 上传成功
		handleAvatarSuccess(response, file, fileList) {
			console.log(this.uploadFile)
			this.$message.success(response.message);
			if (response.status == 0) {
				let length = fileList.length;
				let i = 0;
				for (i; i < length; i++) {
					if (fileList[i].name === file.name) {
						fileList.splice(i, 1);
					}
				}
			} else {
				this.dialogImageUrl = response.data;
				this.loading = false;
				this.uploadFile.push(response.data);
				console.log(this.uploadFile)
			}
		},
		// 发送数据给父组件
		sendData() {
			console.log(this.uploadFile);
			this.$emit('sendImagesMoreData', this.uploadFile);
		}
	},
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>